# -*- coding:utf-8 -*-
# @Time     :2024/3/9 17:04
# @Author   :CHNJX
# @File     :get_log_result.py
# @Desc     :
import datetime
import pandas as pd
from pathlib import Path


def read_logs(log_file_path):
    try:
        with open(log_file_path, 'r', encoding='utf-8') as file:
            return file.readlines()
    except UnicodeDecodeError:
        with open(log_file_path, 'r', encoding='utf-16') as file:
            return file.readlines()


def process_logs(logs, log_file_path):

    # 省略捕获逻辑...
    logs = read_logs(log_file_path)
    log_result, storage_result = "pass", "pass"
    # 定位错误日志行索引
    error_log_indices = [i for i, line in enumerate(logs) if "Lv1" in line or "Lv2" in line]
    # 定位包含“storage”且为错误日志的行索引
    storage_error_indices = [i for i in error_log_indices if "storage" in logs[i].lower()]

    to_capture_general = set()
    to_capture_storage = set()
    storage_error_log_path = None
    error_log_path = None

    # 函数：捕获错误日志周围的日志
    def capture_logs_around(index_set, capture_set):
        for index in index_set:
            start = max(0, index - 10)
            end = min(len(logs), index + 11)

            while True:
                range_set = set(range(start, end))
                new_errors_within_range = range_set.intersection(index_set) - capture_set
                capture_set.update(range_set)

                if not new_errors_within_range or end == len(logs):
                    break

                for new_index in sorted(new_errors_within_range):
                    end = min(len(logs), max(end, new_index + 11))

    # 捕获一般错误日志
    capture_logs_around(error_log_indices, to_capture_general)
    # 捕获包含“storage”的错误日志
    capture_logs_around(storage_error_indices, to_capture_storage)
    if to_capture_general:
        log_result = "fail"
        # 使用Path对象构建新路径
        error_log_path = log_file_path.with_name(log_file_path.stem + "_error.log")
        with open(error_log_path, 'w', encoding='utf-8') as error_file:
            for i in sorted(to_capture_general):
                error_file.write(logs[i])

        # 相关逻辑...
    if to_capture_storage:
        storage_result = 'fail'
        storage_error_log_path = log_file_path.with_name(log_file_path.stem + "_storage_error.log")
        with open(storage_error_log_path, 'w', encoding='utf-8') as storage_error_file:
            for i in sorted(to_capture_storage):
                storage_error_file.write(logs[i])

    print(f"General error logs saved to {error_log_path}")
    if to_capture_storage:
        print(f"Storage error logs saved to {storage_error_log_path}")

    return log_result, storage_result, str(error_log_path) if error_log_indices else None, str(storage_error_log_path) if storage_error_indices else None


def main():
    yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    log_directory = Path(r"\\192.168.253.179\firmware_Submit_Test\log\NVR拷机日志") / yesterday
    log_files = [f for f in log_directory.glob('*.log') if '_error' not in f.stem and '_storage_error' not in f.stem]

    data = {}
    for log_file in log_files:
        logs = read_logs(log_file)
        device_name = log_file.stem.split('_')[0]
        log_result, storage_result, error_log_path, storage_error_log_path = process_logs(logs, log_file)
        data[device_name] = {'硬盘信息': (storage_result, storage_error_log_path), '昨日日志': (log_result, error_log_path)}
    return data


if __name__ == "__main__":
    res = main()
    print(res)
